<template>
  <!-- 个人信息 -->
  <div>
    <el-card class="box-card" style="color:#1f2f3d;user-select: none;">
      <div slot="header" class="clearfix">
        <span>个人信息</span>
      </div>
      <div class="boxx">
        <div class="box-2">
          <span class="p1" style="font-size: 16px">基础信息<span>
              <el-button type="text" class="xg" @click="openUpdateUser()" style="font-size:12px">修改</el-button>
            </span></span>
        </div>
        <div style="text-align:left;margin-top:20px;width:100%;height:220px">
          <div style="float:left;margin-left:20px">
            <img :src="`http://101.43.223.224:8765/image/getImageById?id=${tableDate.img}`" style="width:160px;height:160px">
          </div>
          <div style="float:left;margin-left:20px;margin-top:20px;font-size:14px;color:#909399">
            <div style="height:40px">
              <div style="width:240px;float:left;letter-spacing: 1px;">昵称:&nbsp;<span style="color:#606266">{{tableDate.frontDeskName}}</span></div>
            </div>

            <div style="height:40px">
              <div style="width:240px;float:left;letter-spacing: 1px;">邮箱:&nbsp;<span style="color:#606266">{{tableDate.frontDeskEmail}}</span></div>
              <div style="width:240px;float:left;letter-spacing: 1px;">手机号:&nbsp;<span style="color:#606266">{{tableDate.frontDeskPhone}}</span></div>
            </div>
            <div style="height:40px">
              <div style="letter-spacing: 1px;">地址:&nbsp;<span style="color:#606266">{{tableDate.region}}</span></div>
            </div>
            <div style="height:40px">
              <div style="letter-spacing: 1px;">注册时间:&nbsp;<span style="color:#606266">{{tableDate.createTime}}</span></div>
            </div>
          </div>

        </div>
      </div>
      <div class="boxx2" style="margin-bottom:20px">
        <div style="text-align:left;margin-top:20px;width:100%;">
          <div class="box-3">
          <span class="p1" style="font-size: 16px">手机绑定<span>
              <el-button type="text" class="xg" @click="openUpdateUserPhone()" style="font-size:12px">修改</el-button>
            </span></span>
          </div>
              <p class="p2">
                {{tableDate.frontDeskPhone}}<span><el-button type="text" class="xg" ></el-button></span>
              </p>
            </div>
            <div class="box-3">
              <span class="p1" style="font-size: 16px">邮箱绑定<span>
                  <el-button type="text" class="xg" @click="openUpdateUserEmail()" style="font-size:12px">修改</el-button>
                </span></span>
            </div>
            <p class="p2">
              {{tableDate.frontDeskEmail}}<span><el-button type="text" class="xg" ></el-button></span>
              </p>
      </div>
    </el-card>
    <!-- 修改手机号 -->
    <el-dialog title="修改邮箱" :visible.sync="openUserEmail" width="30%" style="margin-top:30px" :append-to-body=true>
      <el-form :model="userEmailForm"  ref="userEmailForm" :rules="rules">
        <el-form-item label="邮箱" style="width:300px" prop="frontDeskEmail">
          <el-input v-model="userEmailForm.frontDeskEmail" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelUserEmaiForm()">取 消</el-button>
        <el-button type="primary" @click="updateUserEmail()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改手机号 -->
    <el-dialog title="修改手机号" :visible.sync="openUserPhone" width="30%" style="margin-top:30px" :append-to-body=true>
      <el-form :model="userPhoneForm"  ref="userPhoneForm" :rules="rules">
        <el-form-item label="手机号" style="width:300px" prop="frontDeskPhone">
          <el-input v-model="userPhoneForm.frontDeskPhone" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelUserPhoneForm()">取 消</el-button>
        <el-button type="primary" @click="updateUserPhone()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改个人信息-->
    <el-dialog title="修改个人信息" :visible.sync="openUser" width="30%" style="margin-top:30px" :append-to-body=true>
      <el-form :model="userForm"  ref="userForm" :rules="rules">
        <el-form-item label="昵称" style="width:300px" prop="frontDeskName">
          <el-input v-model="userForm.frontDeskName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="详细地址" style="width:300px" prop="region">
          <el-input v-model="userForm.region" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="头像" style="width:300px;height: 300px;" prop="img">
        <br>
          <el-upload class="avatar-uploader" action="" style="width:300px;height: 300px;" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img v-if="img" :src="img" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelUserForm()">取 消</el-button>
        <el-button type="primary" @click="updateUser()">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
export default {
  name: 'PersonalInformation',
  data () {
    return {
      userEmailForm: {},
      userPhoneForm: {},
      openUserPhone: false,
      openUserEmail: false,
      img: '',
      fileImage: '',
      File: File,
      selected: [],
      // 查询个人信息
      tableDate: {},
      // 修改登录名弹窗
      updateLoginNameDialogVisible: false,
      // 是否将弹窗插入至 body 元素。默认将弹窗插入至 body 元素
      shouldAppendToBody: false,
      // 修改昵称表单规则
      userForm: {},
      openUser: false,
      loginId: '',
      userInfo: {},
      rules: {
        frontDeskPhone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ],
        frontDeskEmail: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  mounted () {
    // 获取用户存储的信息
    this.userInfo = JSON.parse(localStorage.getItem('user'))
    if (this.userInfo) {
      this.userInfo = this.userInfo.data
      this.loginId = this.userInfo.id
    }
    // 根据id查询用户信息
    this.selectUserbyId()
  },
  methods: {
    beforeAvatarUpload (file) {
      // 上传图片格式
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是JPG/PNG格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过2MB!')
        return false
      }
      // 赋值
      this.fileImage = file
      this.img = URL.createObjectURL(file)
      // isJPG && isLt2M 自动提交 false 是点击确定后提交
      return false
    },
    // 打开邮箱修改窗口
    openUpdateUserEmail () {
      this.openUserEmail = true
      this.userEmailForm = this.tableDate
    },
    // 打开手机号修改窗口
    openUpdateUserPhone () {
      this.openUserPhone = true
      this.userPhoneForm = this.tableDate
    },
    // 打开修改窗口
    openUpdateUser () {
      this.openUser = true
      this.userForm = this.tableDate
      this.img = 'http://101.43.223.224:8765/image/getImageById?id=' + this.tableDate.img
    },
    handleAvatarSuccess () {},
    cancelUserForm () {
      this.openUser = false
    },
    cancelUserEmaiForm () {
      this.openUserEmail = false
    },
    cancelUserPhoneForm () {
      this.openUserPhone = false
    },
    // 修改邮箱
    updateUserEmail () {
      this.$refs.userEmailForm.validate((valid) => {
        if (valid) {
          this.$axios
            .post('/FrontDeskUser/updateUserByEmail', this.userEmailForm)
            .then((res) => {
              if (res.data.code === 500) {
                this.$message.error('修改不可重复邮箱或邮箱已存在')
              } else {
                this.message('success', '修改邮箱成功')
                this.openUserEmail = false
              }
            })
        }
      })
    },
    // 修改手机号
    updateUserPhone () {
      this.$refs.userPhoneForm.validate((valid) => {
        if (valid) {
          this.$axios
            .post('/FrontDeskUser/updateUserByPhone', this.userPhoneForm)
            .then((res) => {
              if (res.data.code === 500) {
                this.$message.error('修改不可重复手机号或手机号已存在')
              } else {
                this.message('success', '修改手机号成功')
                this.openUserPhone = false
              }
            })
        }
      })
    },
    // 修改用户信息
    updateUser () {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          let isImageChanged = false
          const formData = new FormData()
          formData.append('frontDeskName', this.userForm.frontDeskName)
          formData.append('region', this.userForm.region)
          formData.append('id', this.userForm.id)
          if (this.fileImage) {
            formData.set('file', this.fileImage, this.fileImage.name)
            isImageChanged = true
          }
          // 判断是否修改了图片，若未修改则使用当前的img
          if (!isImageChanged) {
            formData.append('img', this.tableDate.img)
          }
          this.$axios
            .post('/FrontDeskUser/updateUserById', formData)
            .then((res) => {
              if (res.status === 200) {
                this.message('success', '修改个人信息成功')
                this.selectUserbyId()
                this.openUser = false
                // 重新加载当前页面
                this.$router.go(0)
              } else {
                this.$message.error('添加失败')
              }
            })
            .catch((err) => {
              console.log(err)
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 关闭修改地址按钮
    cancelAddress () {
      this.$refs.addressForm.resetFields()
      this.updateAddressDialogVisible = false
      this.bindAddressDialogVisible = false
      this.message('info', '已取消修改地址')
    },
    // 添加点击X关闭是清空from表单数据
    closeExpertFormDialogAddressForm (done) {
      this.$refs.addressForm.resetFields()
      // done 用于关闭 Dialog
      done()
      this.message('info', '已取消修改地址')
    },
    // 打开绑定地址弹窗
    openBindAddress () {
      // this.addressForm = this.addressTableDate
      // if (this.addressTableDate.district !== '') {
      //   this.selected = this.addressTableDate.district.toString().split(',');
      // }
      this.shouldAppendToBody = true
      this.bindAddressDialogVisible = true
    },
    // 验证昵称格式，其他用户是否绑定
    validatorLoginName (loginName, value, callback) {
      const reg = /^[\u4E00-\u9FA5a-zA-Z0-9_-]{4,20}$/
      if (value !== '') {
        if (!reg.test(value)) {
          callback(
            new Error(
              '只能输入中文字、字母、数字、下划线和减号，并且长度为 4 到 20 个字符'
            )
          )
        } else {
          this.$axios
            .get('/user/selectUserByLoginName?loginName=' + value)
            .then((res) => {
              if (res.data.data !== null) {
                if (value === this.tableDate.loginName) {
                  callback()
                } else {
                  callback(new Error('当前昵称已存在'))
                }
              } else {
                callback()
              }
            })
        }
      } else {
        callback()
      }
    },
    // 添加点击X关闭是清空from表单数据
    closeExpertFormDialog (done) {
      this.$refs.form.resetFields()
      // done 用于关闭 Dialog
      done()
      this.message('info', '已取消修改昵称')
    },
    // 根据id查询用户信息
    selectUserbyId () {
      if (this.loginId !== '') {
        this.$axios
          .get(
            '/FrontDeskUser/selectUserbyId?id=' + this.loginId
          )
          .then((res) => {
            if (res.data.flag) {
              this.tableDate = res.data.data
              // localStorage.removeItem('user')
              // localStorage.setItem('user', JSON.stringify(res.data.data))
              // this.message("success", "获取用户个人信息成功");
            } else {
              this.message('error', '获取用户信息失败,请重新登录')
            }
          })
          .catch()
      // eslint-disable-next-line no-empty
      } else {
      }
    }
  }
}
</script>

<style scoped>
/* .area-selected-trigger{
    padding: 0px 20px 7px 12px
  } */
.box-2-p1{
  float: left;
}
.box-2{
    width: 100%;
    height: 40px;
    float: left;
  }
.area-cascader-selected {
  width: 1px;
  line-height: 100%;
}
.box-3 {
  width: 100%;
  height: 100%;
  float: left;
  /* background-color: royalblue; */
  margin-top: 20px;
  text-align: left;
}
.p2 {
  float: left;
  font-size: 18px;
  width: 100%;
  text-align: left;
  height: 40px;
  border-bottom: 1px solid #ccc;
}
.box-2 {
  width: 100%;
  height: 34px;
  background: rgb(249, 249, 252);
  padding-left: 10px;
  margin-bottom: 20px;
  border-radius: 2%;
}
.box-3{
    float: left;
    width: 100%;
    height: 34px;
    background: rgb(249, 249, 252);
    padding-left: 10px;
    margin-bottom: 10px;
    border-radius: 2%;
  }
.xg {
  font-size: 16px;
  margin-left: 6px;
}
.p1 {
  float: left;
}
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
.clearfix span {
  float: left;
}
.box-card {
  min-height:76vh;
  width:90%
}
.box-1 {
  width: 100%;

  /* background-color: aqua; */
}
.xg{
    font-size: 16px;
    margin-left: 6px;
  }
.avatar{
  width:200px;
  height:200px;
}
</style>
